//
//  NetworkService.m
//  QuXiang
//
//  Created by Duncan on 2020/6/17.
//  Copyright © 2020 NanHuaiZi. All rights reserved.
//

#import "NetworkService.h"
#import <YYModel/YYModel.h>

#define kDefault_timeout 60.0f;

@interface NetworkService ()



@end

@implementation NetworkService

+ (instancetype)service {
    static NetworkService *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[NetworkService alloc] init];
    });
    return instance;
}

- (AFHTTPSessionManager *)manager {
    static AFHTTPSessionManager *manager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
//        manager = [[AFHTTPSessionManager alloc] init];
        manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:kAppBaseUrl]];
        AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializer];
        responseSerializer.removesKeysWithNullValues = YES;
        manager.responseSerializer = responseSerializer;
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
        manager.requestSerializer.timeoutInterval = kDefault_timeout;
        
        NSString *token = [DataStoreService getStringById:kDataStoreToken fromTable:User];
        [manager.requestSerializer setValue:token ?: @"" forHTTPHeaderField:@"authorization"];
    });
    return manager;
}

/// 设置token
- (void)setTokenWithHeader {
    NSString *token = [DataStoreService getStringById:kDataStoreToken fromTable:User];
    [self.manager.requestSerializer setValue:token ?: @"" forHTTPHeaderField:@"authorization"];
}

#pragma mark ------- 下载 -------

+ (NSURLSessionDownloadTask * _Nullable)downWithUrlString:(NSString *)urlString
                                         pathString:(NSString *)pathString
                                           progress:(DownloadProgressBlock _Nullable)downloadProgress
                                            success:(ResponSuccessBlock _Nullable)success
                                            failure:(ResponFailBlock _Nullable)failure {
    
    /* 下载地址 */
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    NSURLSessionDownloadTask *downloadTask = [[[NetworkService service] manager] downloadTaskWithRequest:request progress:downloadProgress destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
        /* 设定下载到的位置 */
        return [NSURL fileURLWithPath:pathString];
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        DEBUGLOG(@"completionHandler: %@ --- %@", filePath, error);
        if (error == nil) {
            success(0, filePath, @"下载成功");
        } else {
//            failure(0, error.description);
            failure((int)error.code, error, error.description);
        }
    }];
    
    [downloadTask resume];
    return downloadTask;
}

//+ (URLSessionDataTask * _Nullable)uploadWithFileData:(NSData * _Nullable)fileData
//                                                filePath:(NSString * _Nullable)filePath
//                                                    name:(NSString * _Nonnull)name
//                                                fileName:(NSString * _Nonnull)fileName
//                                                mimeType:(NSString * _Nonnull)mimeType
//                                                 baseUrl:(NSString * _Nullable)baseUrl
//                                                  urlStr:(NSString * _Nonnull)urlStr
//                                              parameters:(NSDictionary * _Nullable)parameters
//                                                progress:(UploadProgressBlock _Nullable)uploadProgress
//                                             success:(ResponSuccessBlock _Nullable)success
//                                             failure:(ResponFailBlock _Nullable)failure {
//    
//    urlStr = baseUrl ? [baseUrl stringByAppendingString:urlStr] : [kCZCURL stringByAppendingString:urlStr];
//    
//    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:urlStr parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//        if (filePath) {
//            [formData appendPartWithFileURL:[NSURL URLWithString:filePath] name:name fileName:fileName mimeType:mimeType error:nil];
//        } else {
//            [formData appendPartWithFileData:fileData name:name fileName:fileName mimeType:mimeType];
//        }
//    } error:nil];
//    
//    NSString *token = USER_DEFAULTS_GET(LYCLoginToken);
//    [request setValue:token ?: @"" forHTTPHeaderField:@"authorization"];
//    
//    URLSessionDataTask *uploadTask = [[[NetworkService service] manager] uploadTaskWithStreamedRequest:request progress:uploadProgress completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
//            
//        if (!error) {
//            
//            DEBUGLOG(@"%@", [responseObject yy_modelToJSONString]);
//            
//            NSDictionary *dictHeader = [responseObject valueForKey:@"Header"];
//            int Code = [dictHeader[@"Code"] intValue];
//            NSString *Msg = kMinQxStr([dictHeader valueForKey:@"Msg"]);
//            
//            if (Code == 1000 || Code == 1005 || Code == 1015 || Code == 1021 || Code == 1028) {
//                id Content = [responseObject valueForKey:@"Content"];
//                
//                if (success) {
//                    success(Code, Content, Msg);
//                }
//                
//            } else {
//                [OCProgress_HUD showErrorWithStatus:Msg];
//                if (failure) {
//                    failure(Code, Msg);
//                }
//                
//                if (Code == 1001 || Code ==  1002) {
//                    [WRUserService logutOutOrTokenOverdue];
//                }
//            }
//                
//        } else {
//            DEBUGLOG(@"%@\n%@", urlStr, error.description);
//            [OCProgress_HUD showErrorWithStatus:@"网络错误，请检查网络"];
//        }
//        
//    }];
//    
//    [uploadTask resume];
//    
//    return uploadTask;
//}

//#pragma mark ------- PUT -------
//
//+ (URLSessionDataTask *_Nullable)putWithUrlEnumName:(RequestUrlInterFace)name
//                                           parameters:(NSDictionary * _Nullable)parameters
//                                        urlParameters:(NSDictionary * _Nullable)urlParameters
//                                              success:(ResponSuccessBlock _Nullable)success
//                                            failure:(ResponFailBlock _Nullable)failure {
//
//    NSString *requestUrl = [NetworkService service].requesFaceDict[@(name)];
//
//    if (urlParameters) {
//        requestUrl = [NSString stringWithFormat:@"%@/%@", requestUrl, urlParameters[@"id"]];
//    }
//
//    NSMutableDictionary *headerDict = [[NSMutableDictionary alloc] init];
//    [headerDict setValue:@"ios" forKey:@"platform"];
//    [headerDict setValue:[NSString getUUIDString] forKey:@"equipment"];
//    [headerDict setValue:@"3984" forKey:@"code"];
//    [headerDict setValue:[UserService getUserToken] forKey:@"token"];
//    [headerDict setValue:[UserService getUserToken] forKey:@"userToken"];
//
//    URLSessionDataTask *session = [[[NetworkService service] manager] PUT:requestUrl parameters:parameters headers:headerDict success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//
//        DEBUGLOG(@"%@%@%@\n%@ \n%@", kAppBaseUrl, requestUrl, headerDict, parameters, [responseObject yy_modelToJSONString]);
//
//        [self analyticalDataWith:responseObject success:success failure:failure];
//
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//
//        failure(task, error);
//        DEBUGLOG(@"%@%@\n%@\n%@\n%@", kAppBaseUrl, requestUrl, headerDict, parameters, error.description);
//        [OCProgress_HUD showErrorWithStatus:@"网络请求失败"];
//    }];
//
//    return session;
//}
//
//#pragma mark ------- DELETE -------
//
//+ (URLSessionDataTask *_Nullable)deleteWithUrlEnumName:(RequestUrlInterFace)name
//                                           parameters:(NSDictionary * _Nullable)parameters
//                                        urlParameters:(NSDictionary * _Nullable)urlParameters
//                                              success:(ResponSuccessBlock _Nullable)success
//                                               failure:(ResponFailBlock _Nullable)failure {
//
//    NSString *requestUrl = [NetworkService service].requesFaceDict[@(name)];
//
//    if (urlParameters) {
//        requestUrl = [NSString stringWithFormat:@"%@/%@", requestUrl, urlParameters[@"id"]];
//    }
//
//    NSMutableDictionary *headerDict = [[NSMutableDictionary alloc] init];
//    [headerDict setValue:@"ios" forKey:@"platform"];
//    [headerDict setValue:[NSString getUUIDString] forKey:@"equipment"];
//    [headerDict setValue:@"3984" forKey:@"code"];
//    [headerDict setValue:[UserService getUserToken] forKey:@"token"];
//    [headerDict setValue:[UserService getUserToken] forKey:@"userToken"];
//
//    URLSessionDataTask *session = [[[NetworkService service] manager] DELETE:requestUrl parameters:parameters headers:headerDict success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//
//        DEBUGLOG(@"%@%@%@\n%@ \n%@", kAppBaseUrl, requestUrl, headerDict, parameters, [responseObject yy_modelToJSONString]);
//
//        [self analyticalDataWith:responseObject success:success failure:failure];
//
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//
//        failure(task, error);
//        DEBUGLOG(@"%@%@\n%@\n%@\n%@", kAppBaseUrl, requestUrl, headerDict, parameters, error.description);
//        [OCProgress_HUD showErrorWithStatus:@"网络请求失败"];
//    }];
//
//    return session;
//
//}

//#pragma mark ------- GET -------
//+ (URLSessionDataTask *)getWithUrlEnumName:(RequestUrlInterFace)name
//                                     success:(ResponSuccessBlock)success
//                                     failure:(ResponFailBlock)failure {
//    return [self getWithUrlEnumName:name parameters:nil urlParameters:nil progress:nil success:success failure:failure];
//}
//
//
//+ (URLSessionDataTask *)getWithUrlEnumName:(RequestUrlInterFace)name
//                                  parameters:(NSDictionary *)parameters
//                                     success:(ResponSuccessBlock)success
//                                     failure:(ResponFailBlock)failure {
//    return [self getWithUrlEnumName:name parameters:parameters urlParameters:nil progress:nil success:success failure:failure];
//}
//
//+ (URLSessionDataTask *)getWithUrlEnumName:(RequestUrlInterFace)name
//                               urlParameters:(NSDictionary *)urlParameters
//                                     success:(ResponSuccessBlock)success
//                                     failure:(ResponFailBlock)failure {
//    return [self getWithUrlEnumName:name parameters:nil urlParameters:urlParameters progress:nil success:success failure:failure];
//}
//
//+ (URLSessionDataTask *)getWithUrlEnumName:(RequestUrlInterFace)name
//                                  parameters:(NSDictionary *)parameters
//                               urlParameters:(NSDictionary *)urlParameters
//                                    progress:(DownloadProgressBlock)downloadProgress
//                                     success:(ResponSuccessBlock)success
//                                     failure:(ResponFailBlock)failure {
//
//
//
//    URLSessionDataTask *session = [[[NetworkService service] manager] GET:[self requestUrl:name urlParameters:urlParameters] parameters:parameters headers:@{} progress:downloadProgress success:success failure:failure];
//
//    return session;
//}

#pragma mark ------- POST -------

+ (void)postJsonDataWithUrlString:(NSString *)urlString
                       parameters:(id)parameters
                          success:(ResponSuccessBlock)success
                          failure:(ResponFailBlock)failure {
    
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.requestSerializer = [AFJSONRequestSerializer serializer];
//    [session POST:urlString parameters:parameters headers:@{} progress:nil success:success failure:failure];
}

+ (URLSessionDataTask *)postWithUrlEnumName:(RequestUrlInterFace)name
                          urlPathParameters:(NSDictionary *)urlPathParameters
                                    success:(ResponSuccessBlock)success
                                    failure:(ResponFailBlock)failure {
    return [self postWithUrlEnumName:name urlPathParameters:urlPathParameters parameters:nil success:success failure:failure];
}

+ (URLSessionDataTask * _Nullable)postWithUrlEnumName:(RequestUrlInterFace)name
                                           parameters:(id _Nullable)parameters
                                              success:(ResponSuccessBlock _Nullable)success
                                              failure:(ResponFailBlock _Nullable)failure {
    return [self postWithUrlEnumName:name urlPathParameters:nil parameters:parameters success:success failure:failure];
}

+ (URLSessionDataTask *)postWithUrlEnumName:(RequestUrlInterFace)name
                            urlPathParameters:(NSDictionary *)urlPathParameters
                                   parameters:(id)parameters
                                      success:(ResponSuccessBlock)success
                                      failure:(ResponFailBlock)failure {
    return [self postWithUrlEnumName:name urlPathParameters:urlPathParameters otherUrlParameters:nil parameters:parameters progress:nil success:success failure:failure];
}

+ (URLSessionDataTask *)postWithUrlEnumName:(RequestUrlInterFace)name
                            urlPathParameters:(NSDictionary *)urlPathParameters
                         otherUrlParameters:(NSDictionary *)otherUrlParameters
                                   parameters:(id)parameters
                                     progress:(DownloadProgressBlock)downloadProgress
                                      success:(ResponSuccessBlock)success
                                      failure:(ResponFailBlock)failure {
    
    NSString *requestUrl = [self requestUrl:name urlParameters:urlPathParameters];
    
    URLSessionDataTask *session = [[[NetworkService service] manager] POST:requestUrl parameters:parameters headers:@{} progress:downloadProgress success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        DEBUGLOG(@"%@%@\n%@ \n%@", kAppBaseUrl, requestUrl, parameters, [responseObject yy_modelToJSONString]);
        
        NSNumber *number = [responseObject valueForKey:@"ret"] ;
        if([number isEqualToNumber:[NSNumber numberWithInt:200]]) {
            
            NSArray *data = [responseObject valueForKey:@"data"];
            int code = [kMinQxStr([data valueForKey:@"code"]) intValue];
            id infos = [[data valueForKey:@"info"] firstObject];
//            id info;
//            if (!kIsEmpty(infos)) {
//                info = [NSString decryptedInformation:infos base64:YES];
//            }
            
            
            NSString *msg = kMinQxStr([data valueForKey:@"msg"]);
    
                                   
            if (code == 0) {
                // (msg.length == 0 || [msg isEqualToString:@"(null)"]) &&
                if (success) {
                    success(code, infos, msg);
                }
                
                
            } else {
                DEBUGLOG(@"code - %d, %@", code, msg);
                
                
                if (code == 700) {
                    [[OCUserService share] logutOutOrTokenOverdue];
                    [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationNeedLogin object:nil];
                    [OCProgress_HUD showErrorWithStatus:msg];
                    
                
                } else {
//                    failure(nil, nil);
                    failure(code, infos, msg);
                    [OCProgress_HUD showErrorWithStatus:msg];
                }
            }
            
        } else {
            DEBUGLOG(@"%@\n%@", requestUrl, [responseObject yy_modelToJSONString]);
            [OCProgress_HUD showErrorWithStatus:kMinQxStr([responseObject valueForKey:@"msg"])];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        failure(task, error);
        failure((int)error.code, error, error.description);
        DEBUGLOG(@"%@%@\n%@\n%@", kAppBaseUrl, requestUrl, parameters, error.description);
        [OCProgress_HUD showErrorWithStatus:@"网络请求失败"];
    }];
    
    return session;
}

+ (NSString *)requestUrl:(RequestUrlInterFace)name urlParameters:(NSDictionary *)parameters {
    
    NSString *url = [NetworkService service].requesFaceDict[@(name)];
    return url;
}

/**
 Json对象转换成Json字符串
 
 @param jsonClass Json对象
 @return Json字符串
 */
+ (NSString *)jsonClassConvertToJosnStringWithJsonClass:(id)jsonClass {
    NSString *resultString;
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonClass options:NSJSONWritingPrettyPrinted error:&error];
    if (error == nil) {
        resultString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    return resultString;
}

#pragma mark ------- 接口 -------

- (NSDictionary *)requesFaceDict {
    if (!_requesFaceDict) {
        _requesFaceDict = @{
            @(None) : @"",
            
        };
    }
    return _requesFaceDict;
}

@end
